#include "./parts.h"
#include "../../device/gpio.h"


namespace driver {

using namespace device::gpio;

using LED1 = PB<0>; // TIM3_CH3
using LED2 = PB<9>; // TIM4_CH4
using LED_STRAW = PB<10>; // TIM2_CH3 AFIO

Parts::Parts() {

    RCC->APB2ENR |= RCC_APB2ENR_IOPBEN;
    RCC->APB1ENR |= RCC_APB1ENR_TIM3EN +
        RCC_APB1ENR_TIM4EN +
        RCC_APB1ENR_TIM2EN;
    
    config_af_pp_out<LED1, LED2, LED_STRAW>();

    TIM3->CR1 = 0x00;
    TIM3->CR2 = 0x00;
    TIM3->PSC = 720 - 1;
    TIM3->ARR = 100 - 1;
    TIM3->CCR3 = 0;
    TIM3->CCMR2 = 0x0060;
    TIM3->CCER = 0x0100;
    TIM3->EGR = 0x01;
    TIM3->CR1 = 0x01;
    
    TIM4->CR1 = 0x00;
    TIM4->CR2 = 0x00;
    TIM4->PSC = 720 - 1;
    TIM4->ARR = 100 - 1;
    TIM4->CCR4 = 0;
    TIM4->CCMR2 = 0x6000;
    TIM4->CCER = 0x1000;
    TIM4->EGR = 0x01;
    TIM4->CR1 = 0x01;

    TIM2->CR1 = 0x00;
    TIM2->CR2 = 0x00;
    TIM2->PSC = 720 - 1;
    TIM2->ARR = 100 - 1;
    TIM2->CCR3 = 0;
    TIM2->CCMR2 = 0x0060;
    TIM2->CCER = 0x0100;
    TIM2->EGR = 0x01;
    TIM2->CR1 = 0x01;
}

void Parts::open_led1() {
    TIM3->CCR3 = 100;
}

void Parts::open_led2() {
    TIM4->CCR4 = 100;
}

void Parts::open_straw() {
    TIM2->CCR3 = 100;
}

void Parts::close_led1() {
    TIM3->CCR3 = 0;
}

void Parts::close_led2() {
    TIM4->CCR4 = 0;
}

void Parts::close_straw() {
    TIM2->CCR3 = 0;
}

void Parts::led1_adj(uint8_t v) {
    TIM3->CCR3 = v;
}

void Parts::led2_adj(uint8_t v) {
    TIM4->CCR4 = v;
}

void Parts::straw_adj(uint8_t v) {
    TIM2->CCR3 = v;
}

}
